<?php


namespace app\lib;


use think\facade\Cache;

class Camera
{
    CONST EXCEPTION_CODE = 1000;
    const APP_KEY = '903e63636b6f497185b5ccead81d39de';
    const APP_SECRET = '377414b523299d9f22ef448c13f344d4';
    CONST TOKEN_NAME = 'camera_token';
    public static $rawResult = [];

    public static function getAccessTOken($isMandatory = false)
    {
        $token = Cache::get(self::TOKEN_NAME);
        if ($token && !$isMandatory) {
            return $token;
        }

        $result =  self::validateResul(curl_post('https://open.ys7.com/api/lapp/token/get', [
            'appKey' => self::APP_KEY,
            'appSecret' => self::APP_SECRET,
        ]),__FUNCTION__, func_get_args());
        Cache::set(self::TOKEN_NAME, $result['data']['accessToken'], 3600 * 24 * 6);
        return Cache::get(self::TOKEN_NAME);
    }

    public static function createDevice($token, $deviceSerial, $validateCode)
    {
        $data = self::getAccessTOken();
        $result = self::validateResul(curl_post('https://open.ys7.com/api/lapp/device/add', [
            'accessToken' => $token,
            'deviceSerial' => $deviceSerial,
            'validateCode' => $validateCode,
        ]), __FUNCTION__, func_get_args());
        return $result;
    }

    public static function validateResul($result, $functionName, $args, $msg = 'error')
    {
        $result = json_decode($result, true);
        self::$rawResult = $result;
        if (!is_array($result) || $result['code'] != 200) {
            if ($result['code'] == 10002) { // accessToken异常或过期，重新获取调用
                return self::createDevice(self::getAccessTOken(true), ...$args);
            }
            throw new \Exception($msg, self::EXCEPTION_CODE);
        }
        return $result;
    }

    public static function getRawResult()
    {
        return self::$rawResult;
    }
}